import json
import random

from django.conf import settings
from django_redis import get_redis_connection
from ronglian_sms_sdk import SmsSDK

# 发送验证码
def send_sms(mobile):
    # ------------ 判断是否可以发送验证码 --------------
    # 连接redis
    redis = get_redis_connection("sms_code")
    # ttl结果不为-2表示验证码发送间隔未满
    if redis.ttl(f"dingxiang_interval_{mobile}") != -2:
        return 0
    # ------------- 容联云发送验证码 --------------
    # 获取settings
    ronglianyun = settings.RONGLIANYUN
    # 获取短信模板
    tid = ronglianyun.get("reg_tid")
    # 获取短信发送间隔
    sms_interval = ronglianyun.get("sms_interval")
    # 发送间隔，配置文件中已秒为单位，容联云中以分钟为单位
    interval = sms_interval / 60

    # 生成验证码
    code = f"{random.randint(0, 9999):04d}"
    # 生成发送短信的data(验证码, 发送间隔)
    data = (code, interval)

    # 获取容联云账户信息
    sdk = SmsSDK(ronglianyun.get("accId"), ronglianyun.get("accToken"), ronglianyun.get("appId"))
    # 发送(未使用celery)
    # response = sdk.sendMessage(tid, mobile, data)
    # 将容联云返回的json数据转为字典格式
    # response = json.loads(response)
    # print(response)
    # ------------- 容联云发送验证码 --------------

    # ------------- 将验证码存入redis，判断发送间隔和有效时间 -----------
    # 获取短信有效时间
    sms_expire = ronglianyun.get("sms_expire")
    pipe = redis.pipeline()
    pipe.multi()
    # 设置验证码有效时间：key       持续时间n秒   value
    print(code)
    print(sms_interval)
    print(type(sms_interval))
    redis.setex(f"dingxiang_sms_{mobile}", sms_expire, code)
    redis.setex(f"dingxiang_interval_{mobile}", sms_interval, "-")
    pipe.execute()
    return 1
    # ------------- 将验证码存入redis，判断发送间隔和有效时间 -----------
